package annotion;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Created by Shirly on 2016/10/8.
 */
public class testAnnoation {
    public static void main(String[] args) {
        filer1 filer22 = new filer1();
        filer22.setAge(12);

        filer1 filer33 = new filer1();
        filer33.setId("1234545454,dadadada,daadadda");
        System.out.println(querySql(filer22));
        System.out.println(querySql(filer33));

    }

    public static String querySql(Object o) {
        Class c = o.getClass();
        String biaoName = null;
        boolean typeAnnotion = c.isAnnotationPresent(table.class);
        if (!typeAnnotion) {
            return null;
        }
        table a = (table) c.getAnnotation(table.class);
        biaoName = a.value();
        StringBuffer sb = new StringBuffer();
        sb.append("select *from ").append(biaoName).append(" where 1 =1");

        Field[] ms = c.getDeclaredFields();
        for (Field f : ms ){
       boolean methodAnnotion = f.isAnnotationPresent(colum.class);
            if(!methodAnnotion){
                continue;
            }
            colum b = (colum)f.getAnnotation(colum.class);
            String colum =b.value();
            String columMethod = "get"+f.getName().substring(0,1).toUpperCase()+f.getName().substring(1);
            try {
                Method method = c.getMethod(columMethod);
               Object ooo = method.invoke(o);
                if(ooo ==null || (ooo instanceof Integer && (Integer)ooo ==0)){
                    continue;
                }
                sb.append(" and ").append(colum);
                if(ooo instanceof  String){
                    if(((String) ooo).contains(",")){
                        String [] ss = ((String) ooo).split(",");
                        sb.append(" in(");
                        for (String s :ss){
                            sb.append("'").append(s).append("'").append(",");
                        }
                        sb.deleteCharAt(sb.length()-1);
                        sb.append(")");
                    }
                }else{
                   sb.append("=").append(ooo);
                }

            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        }

        return sb.toString();
    }

}
